//传进来的auto是为了区分自动更新和手动更新, auto : 0 - 自动更新   1 - 不自动更新
window.updater = {

    _alert: function (data, ok, cancel) {
        apix.confirm({
            title: '发现新版本',
            msg: '是否安装最新版本' + data.version + '？\r\n' + data.notes,
            btnCap: {
                ok: isIOS() ? '升级' : '安装',
                cancel: isIOS() ? '取消' : '放弃',
            },
            onOK: function() {
                ok && ok();
            },
            onCancel: function(){
                cancel && cancel();
            }
        });
    },

    // 手动调用更新
    makeUpdate: function () {
        var _this = this;
        utils.loading();
        fajax_get('wuchen/appcfg/update.php', {}, {
            always: function() {
                utils.rmLoading();
            },
            succ: function(json) {
                if (isIOS()) {
                    if (api.appVersion != json.data.version) {
                        _this._alert({version:json.data.version, notes: json.data.notes}, function () {
                            var openLastPage = api.require('openLastPage');
                            openLastPage.openScheme({url: "https://itunes.apple.com/cn/app/id1453976897?mt=8"});
                        });
                    }
                    return;
                }
                var need = json.data.needupdate;
                if (1 == need) {
                    var savePath = $apix.getStorage('savePath');
                    var now = Date.parse(new Date());
                    var updateInfo = $apix.getStorage('updateInfo') || '';
                    var version = $apix.getStorage('version');
                    if(version && version == json.data.version){
                        _this._alert({version:version, notes: updateInfo}, function () {
                            api.installApp({
                                appUri : savePath
                            });
                        });
                    }else {
                        this._doTry(json.data,false);
                    }
                } else {
                    alert('已是最新版本，无需更新');
                }
            },
            fail: function(json, url) {
                utils.toast(json.msg);
            }
        })
    },

    tryUpdate: function(auto, dv) {
        var _this = this;
        if(!auto){
            utils.loading();
        }

        var data = {};
        if (obj_being(dv)) {
            data = {
                'serial': dv.rawId,
                'type': dv.rawType
            };
        }
        fajax_post('wuchen/appcfg/update.php', data, {
            always: function() {
                utils.rmLoading();
            },
            succ: function(json) {
                var need = json.data.needupdate;
                if (1 == need) {
                    _this.checkDown(json,auto);
                } else {
                    if(!auto){
                        alert('已是最新版本，无需更新');
                    }
                }
            },
            fail: function(json, url) {
                utils.toast(json.msg);
            }
        });
    },
    checkDown: function(json,auto){
        var _this = this;
        var savePath = $apix.getStorage('savePath');
        var now = Date.parse(new Date());
        var timestamp = $apix.getStorage('timestamp');
        var updateInfo = $apix.getStorage('updateInfo') || '';
        var version = $apix.getStorage('version');
        if(version && version == json.data.version){
            if(now - window.dynCfg.downLoadNotice() > timestamp){
                $apix.setStorage('timestamp',now);
                _this._alert({version:version, notes: updateInfo}, function () {
                    api.installApp({
                        appUri : savePath
                    });
                });
            }
        }else{
            this._doTry(json.data,auto);
        }

    },
    _doTry: function(pkg,auto) {
        var _this = this;
        if(!auto){
            apix.confirm({
                title: '发现新版本',
        		msg: '确定升级到最新版本' + pkg.version + '？',
        		btnCap: {
        			ok: '升级',
        			cancel: '放弃',
        		},
        		onOK: function() {
                    _this._doUpdate(pkg);
        		}
            });
        }else{
            _this._doUpdate(pkg,auto);
        }

    },

    _doUpdate: function(pkg,auto) {
        // https://docs.apicloud.com/Dev-Guide/version_update
        var _this = this;
        api.download({
            url: pkg.package,
            report: true
        }, function(ret, err) {
            if (obj_being(ret)) {

                if (0 == ret.state && !auto) {/* 下载进度 */
                    utils.loading('已下载' + Math.floor(ret.percent) + '%');
                }

                if (1 == ret.state) {/* 下载完成 */
                    var timestamp = Date.parse(new Date());
                    var savePath = ret.savePath;
                    $apix.setStorage('timestamp',timestamp)
                    $apix.setStorage('savePath',savePath)
                    $apix.setStorage('version',pkg.version);
                    $apix.setStorage('updateInfo',pkg.notes);
                    if(!auto){
                        utils.rmLoading();
                        api.installApp({
                            appUri : savePath
                        });
                    }else{
                        _this._alert({version:pkg.version, notes: pkg.notes}, function () {
                            api.installApp({
                                appUri : savePath
                            });
                        });
                    }

                } else if (2 == ret.state) {/* 下载失败 */
                    utils.rmLoading();
                    alert('安装包下载失败，请联系客服');
                }
            }
        });
    }
}
